package com.daaij.seventhchapter;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 多线程排序例程
 */
public class MultiThreadSort {

    private int threadNum = 8;

    /**
     * 线程池大小
     * 线程池生成，销毁策略
     * 线程生成策略
     * 任务顺序处理，逻辑关联。
     * 任务失败处理
     * TODO，到时候配合java多线程编程思考一下
     *
     */
    private ExecutorService[] executors;

    public MultiThreadSort(){

    }

    public MultiThreadSort(int threadNum){
        this.threadNum = threadNum;
    }

    public void init(){
        executors = new ExecutorService[threadNum];
        initExecutors();
    }

    private void initExecutors() {
        for(int i = 0 ;i < executors.length;i ++){
            executors[i] = Executors.newSingleThreadExecutor();
        }
    }

    class QuickSortTask<T> implements Runnable{

        int start;
        int end;
        List<T> input;
        Comparator<T> comparator;


        public QuickSortTask(int start, int end, List<T> input, Comparator<T> comparator) {
            this.start = start;
            this.end = end;
            this.input = input;
            this.comparator = comparator;
        }

        @Override
        public void run() {
            if(start >= end){
                if(end >= input.size() - 1){
                    System.out.println(System.currentTimeMillis());
                    //System.out.println(input);
                }
                return;
            }
            int ascIndex = Sort.doThisRoundQuickSort(start,end,input,comparator);

            int threadIndex = (start + ascIndex - 1) % threadNum;
            ExecutorService service = executors[threadIndex];
            //task一定要new
            service.execute(new QuickSortTask<T>(start,ascIndex - 1,input,comparator));

            int threadIndex1 = (ascIndex + 1 + end) % threadNum;
            ExecutorService service1 = executors[threadIndex1];
            service1.execute(new QuickSortTask<T>(ascIndex + 1,end,input,comparator));
        }
    }

    public <T>void quickSort(int start, int end, List<T> input, Comparator<T> comparator){
        int threadIndex = (start + end) % threadNum;
        ExecutorService service1 = executors[threadIndex];
        service1.execute(new QuickSortTask<T>(start,end,input,comparator));
    }

    public static void main(String[] args){

        //MultiThreadSort multiThreadSort = new MultiThreadSort();
        //multiThreadSort.init();
        //multiThreadSort

    }




}
